<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 顶部工具栏 -->
      <page-tools :show-before="false">
        <template v-slot:after>
          <el-button type="primary" size="mini" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" size="mini" @click="onExcelExport">导出</el-button>
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 放置表格和分页 -->
      <el-card>
        <el-table :data="employees" border>
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <img
                v-imgError="require('../../assets/common/bigUserHeader.png')"
                class="avatar"
                :src="row.staffPhoto"
                @click="onClickAvatar(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" sortable>
            <template v-slot="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column label="部门" sortable>
            <template v-slot="{row}">
              {{ row.departmentName || '暂未设置' }}
            </template>
          </el-table-column>
          <el-table-column label="入职时间">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable>
            <template v-slot="scope">
              {{ scope.row.enableState ? '可用' : '不可用' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button :disabled="checkPermission(points.pointUserUpdate)" type="text" size="small" @click="$router.push('/employees/' + row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button :disabled="checkPermission(points.pointUserSetJob)" type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="onClickRole(row.id)">角色</el-button>
              <el-button :disabled="checkPermission(points.pointUserDelete)" type="text" size="small" @click="onClickDel(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :total="total" :page-size="tablePage.size" layout="total, prev, pager, next" @current-change="handleCurrentChange" />
        </el-row>
      </el-card>
    </div>
    <AddEmployees :show-dialog.sync="showDialog" @add-success="loadEmployees" />
    <!-- <AddEmployees v-model="showDialog" /> -->
    <!-- 当前组件一创建 dialog组件 也跟着创建了,但是里面的内容没有创建出来, dialog显示 内容才会创建-->
    <el-dialog :visible.sync="qrcodeDialog">
      <!-- 用来绘制二维码 -->
      <canvas id="qrcode" />
    </el-dialog>

    <!-- 角色管理弹框 -->
    <assign-role :set-role-dialog.sync="setRoleDialog" :employees-id="currentEmployeesId" />
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees.js'
import AddEmployees from './components/add-employees.vue'
import { formatHireType } from '@/filters'
import { formatDate } from '@/utils'
import QRCode from 'qrcode'
import AssignRole from './components/assign-role'
import permissionMix from '@/mixins/permission'
console.dir(QRCode)
export default {
  name: 'Employees',

  components: {
    AddEmployees,
    AssignRole
  },

  mixins: [permissionMix],
  data() {
    return {
      tablePage: {
        page: 1,
        size: 5
      },
      total: 0,
      employees: [],
      showDialog: false,
      qrcodeDialog: false,
      setRoleDialog: false,
      currentEmployeesId: ''
    }
  },

  created() {
    this.loadEmployees()
    // 2 正式 3 非正式
    this.type = 1
  },

  mounted() {
  },

  methods: {
    async loadEmployees() {
      const res = await getEmployeesList(this.tablePage)
      this.total = res.total
      this.employees = res.rows
    },
    handleCurrentChange(val) {
      console.log(val)
      this.tablePage.page = val
      this.loadEmployees()
    },
    // 点击了删除
    onClickDel(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 点击了确定
        await delEmployee(row.id)
        this.$message.success('删除成功')
        this.loadEmployees()
      }).catch(() => {})
    },
    // 导出excel
    onExcelExport() {
      // export_json_to_excel()
      // 懒加载引入
      import('@/vendor/Export2Excel').then(async excel => {
        // excel是一个对象包含了: @/vendor/Export2Excel改文件中暴漏的数据
        const res = await getEmployeesList({ page: 1, size: this.total })
        const mapKey = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const tHeader = Object.keys(mapKey)
        const arr = this.formatExcelData(res.rows, tHeader, mapKey)
        // [['震惊..', '老高'], ['震惊...', '小高']]
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data: arr, // 具体数据 必填
          filename: '河马员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2']
        })
      })
    },
    // 将数据格式化成excel所需要的数据
    formatExcelData(data, tHeader, mapKey) {
      return data.map(item => {
        // tHeader:  ['姓名', '手机号', '入职日期']
        return tHeader.map(headerItem => {
          if ((item[mapKey[headerItem]] - 0) > 0 && (headerItem === '入职日期' || headerItem === '转正日期')) {
            return formatDate(item[mapKey[headerItem]], '/')
          } else if (headerItem === '聘用形式') {
            return formatHireType(item[mapKey[headerItem]])
          }
          return item[mapKey[headerItem]]
        })
      })
    },
    // 点击头像
    onClickAvatar(imgUrl) {
      console.log(imgUrl)
      if (!imgUrl) return this.$message.error('该用户还未设置头像')
      // 数据变了 数据驱动视图>异步的
      this.qrcodeDialog = true

      // 等视图更新
      this.$nextTick(() => {
        const canvas = document.getElementById('qrcode')
        QRCode.toCanvas(canvas, imgUrl, function(error) {
          if (error) return this.$message.error('生成失败')
        })
      })
    },
    // 点击分配角色
    onClickRole(employeesId) {
      this.setRoleDialog = true
      this.currentEmployeesId = employeesId
    }
  }
}
</script>

<style scoped lang='scss'>
.avatar {
  width: 100px;
  height: 100px;
}

::v-deep .el-dialog__body {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
